package cn.edu.hqu.cst.android.service;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    String TAG = "MainActivity";
    Button btnBindService, btnUnbindService, btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind = false;
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serviceBinder = (MyService.MyServiceBinder) service;
            Log.d(TAG, "Service is connected");

            //返回 Service 的 Binder 对象
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "Service is disconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnBindService = findViewById(R.id.btn_main_activity_bind_service);
        btnUnbindService = findViewById(R.id.btn_main_activity_unbind_service);
        btnGetStatus = findViewById(R.id.btn_main_activity_get_status);
        tvServiceStatus = findViewById(R.id.tv_main_activity_service_status);
        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, MyService.class);
        switch (v.getId()) {
            case R.id.btn_main_activity_bind_service:
                if (!isServiceBind) {
                    intent.setClass(this, MyService.class);
                    bindService(intent, conn, Service.BIND_AUTO_CREATE);
                }
                //如果 service 尚未绑定就绑定，如果已经绑定则忽略
                break;

            case R.id.btn_main_activity_get_status:

                Toast.makeText(MainActivity.this, "Service的Count值为" + serviceBinder.getCount(), Toast.LENGTH_LONG).show();
//如果 service 已经绑定，获取 service 的 count 计数并显示在界面上。
                break;


            case R.id.btn_main_activity_unbind_service:

                    intent.setClass(this, MyService.class);
                    unbindService(conn);


//如果 service 已经绑定，则可以解绑，否则忽略
                break;
        }
    }
}